import os
import urllib

import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from entities import Category
from entities import Entities
from Entities import *
from Entities import Developer
from Entities import Language
import entities
from Entities import Version
from Entities import Device
from datetime import date
import datetime
from google.appengine.api import images
from google.appengine.ext import blobstore


def Add(title,appName,description,price,keyWord,languageID,CategoryID,DeviceID,devID,releaseDate,versionID,appIcon,appScreenShot,downloadNumber,appSource):
    language = Language.get_by_id(languageID)
    category = Entities.Category.get_by_id(CategoryID)
    developer = Developer.get_by_id(devID)
    version = Version.get_by_id(versionID)
    device = Device.get_by_id(DeviceID)
    releasedate = datetime.datetime.strptime(releaseDate,"%m/%d/%Y" )
    appCheck = db.GqlQuery("SELECT * FROM App WHERE AppName = :1",appName)
    if appCheck.count() == 0:
        app = App(Title = title,AppName = appName,Description = description,Price = price,
                KeyWord = keyWord,LanguageID = language,CategoryID = category,DeviceID = device,DevID = developer,
                ReleaseDate = releasedate,VersionID = version,AppIcon = appIcon,AppScreenShot = appScreenShot,DownloadNumber = downloadNumber,AppSource = appSource)
        app.put()
        return 1
    else:
        return 0

def Update(AppID,appName,description,price,keyWord,languageID,CategoryID,DevID,releaseDate,minVersion,appIcon,appScreenShot,downloadNumber):
    app_update = App.get_by_id(AppID)
    language = Language.get_by_id(languageID)
    category = Entities.Category.get_by_id(CategoryID)
    developer = Developer.get_by_id(DevID)
    if app_update.count() > 0:
        app_update.AppName = appName
        app_update.Description = description
        app_update.Price = price
        app_update.KeyWord = keyWord
        app_update.LanguageID = language
        app_update.CategoryID = category
        app_update.DevID = developer
        app_update.ReleaseDate = releaseDate
        app_update.MinVersion = minVersion
        app_update.AppIcon = appIcon
        app_update.AppScreenShot = appScreenShot
        app_update.DownloadNumber = downloadNumber
        app_update.put()
        return "Complete"
    else:
        return "No ..."
      
def GetbyName(appName):
    app_list = []
    apps = db.GqlQuery("SELECT * FROM App WHERE AppName = :1",appName)
    for app in apps:
        app_dict = {}
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = app.Description
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageID"] = app.LanguageID
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryID"] = app.CategoryID
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["Developer"] = app.DevID
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["Version"] = app.VersionID
        app_dict["AppIcon"] = app.AppIcon
        app_dict["AppScreenShot"] = app.AppScreenShot
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_list.append(app_dict)
    tuple_app = tuple(app_list) 
    return tuple_app

# Khong truyen duoc Text, kinh nghiem xuong mau --> phai truyen ve string.    
def GetAllApp(domain):
    app_list = []
    apps = App.all()
    for app in apps:
        app_dict = {}
        app_dict["Key"] = str(app.key())
        app_dict["id"] = app.key().id()
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = str(app.Description)
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["VersionName"] = app.VersionID.VersionName
        app_dict["AppIcon"] = str(app.AppIcon.key())
        app_dict["linkIcon"] = domain + "/icon/" + str(app_dict["id"])
        app_dict["AppScreenShot"] = str(app.AppScreenShot.key())
        app_dict["linkScreenShot"] = domain + "/screen/" + str(app_dict["id"])
        app_dict["AppSource"] = str(app.AppSource.key())
        app_dict["linkSource"] = domain + "/app/"+str(app_dict["id"])
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_dict["PaypalAccount"] = app.DevID.PaypalAccount
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app

def GetTopApp(domain,isFree,isMobile):
    app_list = []
    if isFree == 1:
        if isMobile == 1:
            apps = db.GqlQuery("SELECT * FROM App WHERE Price =:1 ORDER BY DownloadNumber DESC LIMIT 50",0.0)
        else:
            apps = db.GqlQuery("SELECT * FROM App WHERE Price =:1 ORDER BY DownloadNumber DESC LIMIT 5",0.0)
    else:
        if isMobile == 1:
            apps = db.GqlQuery("SELECT * FROM App WHERE Price != :1 ORDER BY Price,DownloadNumber DESC LIMIT 50",0.0)
        else:
            apps = db.GqlQuery("SELECT * FROM App WHERE Price != :1 ORDER BY Price,DownloadNumber DESC LIMIT 5",0.0)
    for app in apps:
        app_dict = {}
        app_dict["Key"] = str(app.key())
        app_dict["id"] = app.key().id()
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = str(app.Description)
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["VersionName"] = app.VersionID.VersionName
        app_dict["AppIcon"] = str(app.AppIcon.key())
        app_dict["linkIcon"] = domain + "/icon/" + str(app_dict["id"])
        app_dict["AppScreenShot"] = str(app.AppScreenShot.key())
        app_dict["linkScreenShot"] = domain + "/screen/" + str(app_dict["id"])
        app_dict["AppSource"] = str(app.AppSource.key())
        app_dict["linkSource"] = domain + "/app/"+str(app_dict["id"])
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_dict["PaypalAccount"] = app.DevID.PaypalAccount
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app
    
def GetbyCategory(domain,categoryName):
    category = entities.Category.GetbyName(categoryName)
    app_list = []
    apps = db.GqlQuery("SELECT * FROM App WHERE CategoryID =:1",category)
    for app in apps:
        app_dict = {}
        app_dict["Key"] = str(app.key())
        app_dict["id"] = app.key().id()
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = str(app.Description)
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["VersionName"] = app.VersionID.VersionName
        app_dict["AppIcon"] = str(app.AppIcon.key())
        app_dict["linkIcon"] = domain + "/icon/" + str(app_dict["id"])
        app_dict["AppScreenShot"] = str(app.AppScreenShot.key())
        app_dict["linkScreenShot"] = domain + "/screen/" + str(app_dict["id"])
        app_dict["AppSource"] = str(app.AppSource.key())
        app_dict["linkSource"] = domain + "/app/"+str(app_dict["id"])
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_dict["PaypalAccount"] = app.DevID.PaypalAccount
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app
    
def GetHotApp(domain,isMobile):
    app_list = []
    if isMobile == 1:
        apps = db.GqlQuery("SELECT * FROM App ORDER BY DownloadNumber DESC LIMIT 50")
    else:
        apps = db.GqlQuery("SELECT * FROM App ORDER BY DownloadNumber DESC LIMIT 5")
    for app in apps:
        app_dict = {}
        app_dict["Key"] = str(app.key())
        app_dict["id"] = app.key().id()
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = str(app.Description)
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["VersionName"] = app.VersionID.VersionName
        app_dict["AppIcon"] = str(app.AppIcon.key())
        app_dict["linkIcon"] = domain + "/icon/" + str(app_dict["id"])
        app_dict["AppScreenShot"] = str(app.AppScreenShot.key())
        app_dict["linkScreenShot"] = domain + "/screen/" + str(app_dict["id"])
        app_dict["AppSource"] = str(app.AppSource.key())
        app_dict["linkSource"] = domain + "/app/"+str(app_dict["id"])
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_dict["PaypalAccount"] = app.DevID.PaypalAccount
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app
    
def GetNewApp(domain,isMobile):
    app_list = []
    if isMobile ==1:
        apps = db.GqlQuery("SELECT * FROM App ORDER BY ReleaseDate DESC LIMIT 50")
    else:
        apps = db.GqlQuery("SELECT * FROM App ORDER BY ReleaseDate DESC LIMIT 5")
    for app in apps:
        app_dict = {}
        app_dict["Key"] = str(app.key())
        app_dict["id"] = app.key().id()
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = str(app.Description)
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["VersionName"] = app.VersionID.VersionName
        app_dict["AppIcon"] = str(app.AppIcon.key())
        app_dict["linkIcon"] = domain + "/icon/" + str(app_dict["id"])
        app_dict["AppScreenShot"] = str(app.AppScreenShot.key())
        app_dict["linkScreenShot"] = domain + "/screen/" + str(app_dict["id"])
        app_dict["AppSource"] = str(app.AppSource.key())
        app_dict["linkSource"] = domain + "/app/"+str(app_dict["id"])
        app_dict["DownloadNumber"] = app.DownloadNumber
        app_dict["PaypalAccount"] = app.DevID.PaypalAccount
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app
    
def GetbyDev(devID):
    developer = Developer.get_by_id(devID)
    app_list = []
    apps = db.GqlQuery("SELECT * FROM App WHERE DevID =:1",developer)
    for app in apps:
        app_dict = {}
        app_dict["Key"] = app.key()
        app_dict["id"] = app.key().id()
        app_dict["Title"] = app.Title
        app_dict["AppName"] = app.AppName
        app_dict["Description"] = app.Description
        app_dict["Price"] = app.Price
        app_dict["KeyWord"] = app.KeyWord
        app_dict["LanguageID"] = app.LanguageID
        app_dict["LanguageName"] = app.LanguageID.LanguageName
        app_dict["CategoryID"] = app.CategoryID
        app_dict["DeviceName"] = app.DeviceID.DeviceName
        app_dict["CategoryName"] = app.CategoryID.CategoryName
        app_dict["Developer"] = app.DevID
        app_dict["ReleaseDate"] = app.ReleaseDate
        app_dict["Version"] = app.VersionID
        app_dict["AppIcon"] = app.AppIcon.key()
        app_dict["AppScreenShot"] = app.AppScreenShot.key()
        app_dict["AppSource"] = app.AppSource.key()
        app_dict["DownloadNumber"] = app.DownloadNumber
        blob_key = str(urllib.unquote(str(app_dict["AppSource"])))
        app_dict["Size"] = round(((blobstore.BlobInfo.get(blob_key)).size)/1024.0,1)
        app_list.append(app_dict)
    tuple_app = tuple(app_list)
    return tuple_app
    
def Download(AppID):
    status_list = []
    try:
        status_dict = {}
        app_update = App.get_by_id(AppID)
        app_update.DownloadNumber = app_update.DownloadNumber + 1
        app_update.put()
        status_dict["result"]=1
        status_list.append(status_dict)
    except:
        status_dict = {}
        status_dict["result"]=0
        status_list.append(status_dict)
    tuple_status = tuple(status_list)
    return tuple_status
        
def Delete(AppID):
    app = App.get_by_id(AppID)
    if app.count() > 0 :
        App.delete(app)
        return "Complete"
    else :
        return "No ..."
    
